'use strict';
const Client = require('ftp');
const fs = require('fs');
const path = require('path');
// connect to localhost:21 as anonymous
const config = {
  host: '192.168.10.22',
  port: 21,
  user: 'myuser',
  password: 'mypass',
  timeout: 50000,
};
//   c.connect(config);

// host - string - The hostname or IP address of the FTP server. Default: 'localhost'

// port - integer - The port of the FTP server. Default: 21

// secure - mixed - Set to true for both control and data connection encryption, 'control' for control connection encryption only, or 'implicit' for implicitly encrypted control connection (this mode is deprecated in modern times, but usually uses port 990) Default: false

// secureOptions - object - Additional options to be passed to tls.connect(). Default: (none)

// user - string - Username for authentication. Default: 'anonymous'

// password - string - Password for authentication. Default: 'anonymous@'

// connTimeout - integer - How long (in milliseconds) to wait for the control connection to be established. Default: 10000

// pasvTimeout - integer - How long (in milliseconds) to wait for a PASV data connection to be established. Default: 10000

// keepalive - integer - How often (in milliseconds) to send a 'dummy' (NOOP) command to keep the connection alive. Default: 10000

const myFTP = {
  ftpConnection: null,
  connect(options) {
    return new Promise((resolve, reject) => {
      try {
        const c = new Client();
        c.on('ready', () => {
          console.log('ready');
          this.ftpConnection = c;
          resolve(true);
        });
        c.connect(options);
        console.log('=============================')
        console.log(JSON.stringify(options))
        console.log('=============================')
        setTimeout(() => reject('connection timeout'), options.timeout || 3000);
      } catch (error) {
        console.log("ftp打印一个错误:",error)
      }
    });
  },
  list() {
    return new Promise((resolve, reject) => {
      this.ftpConnection.list((err, list) => {
        if (err) reject(err);
        resolve(list);
        // this.ftpConnection.end();
      });
    });
  },
  upload(source, dest) {
    return new Promise((resolve, reject) => {
      this.ftpConnection.put(source, dest, err => {
        if (err) reject(err);
        resolve(true);
        // this.ftpConnection.end();
      });
    });
  },
  download(source, local) {
    const { dir } = path.parse(local);
    fs.mkdirSync(dir, { recursive: true });
    return new Promise((resolve, reject) => {
      console.log('==下载==',source)
      this.ftpConnection.get(source, (err, stream) => {
        if (err) reject(err);
        stream.once('close', () => {
          // this.ftpConnection.end();
          console.log('123')
          resolve(true);
        });
        stream.on('finish', () => {
          console.log('下载完成了')
          resolve(true);
        });
        stream.pipe(fs.createWriteStream(local));
      });
    });
  },
  mkdir(path, recursive) {
    return new Promise((resolve, reject) => {
      this.ftpConnection.mkdir(path, recursive, err => {
        // this.ftpConnection.end();
        return err ? reject(err) : resolve(true);
      });
    });
  },
  delete(path) {
    return new Promise((resolve, reject) => {
      this.ftpConnection.delete(path, err => {
        // this.ftpConnection.end();
        return err ? reject(err) : resolve(true);
      });
    });
  },
  close() {
    return new Promise(resolve => {
      this.ftpConnection.end();
      resolve(true);
    });
  },
};

// async function main() {
//   try {
//     const result = await myFTP.connect(config);
//     console.log(`连接${result}`);
//     if (result) {
//       const list = await myFTP.list();
//       console.log(list);
//       const res = await myFTP.download('helloworld.txt', 'helloworld.txt');
//       console.log('download', res);
//       const up = await myFTP.upload('helloworld.txt', 'test.txt');
//       console.log('up', up);
//     }
//   } catch (error) {
//     console.log(error);
//   }
// }
// main();

module.exports = myFTP;
